import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Image, ScrollView, Video } from '@tarojs/components';

import { assetsFileUrl } from '../../api/client';
import ScoreStar from '../../components/scoreStar';
import PageHeader from '../../components/pageHeader';
import ImageLoader from '../../components/ImageLoader';
import LicenseTags from '../../components/LicenseTags';
import DataErrorView from '../../components/dataError';
import EmptyContent from '../../components/emptyContent';
import UserGenderImage from '../../components/userGender';
import DataLoadingView from '../../components/dataLoading';
import { UserAvatarImage } from '../../components/userAvatar';
import { CoachDetailItem, CoachPriceItem, CoachCommentItem, CommentAttachmentItem } from '../../types/coach';
import { 
  getCoachDetailApi, getCoachPricesApi, getCoachHonorWallApi, setCoachCommentFavoriteApi,
  getCoachCommentsApi, deleteCommentOrReplyApi, getCoachSessionIdApi
} from '../../api/coachApi';

import './index.scss';



/**
 * 教练详情页面组件
 * 展示教练的详细信息、价格套餐、荣誉墙、学员评价等内容
 */
const CoachDetailPage: React.FC = () => {
  const pageSize: number = 20;
  // 使用ref标记是否已初始化数据
  const isInitialized = useRef(false);
  const isRequesting = useRef<boolean>(false);
  const routerParams = Taro.getCurrentInstance().router?.params;
  const baseId = routerParams?.baseId ? Number(routerParams.baseId) : 0;
  const coachId = routerParams?.coachId ? Number(routerParams.coachId) : 0;

  // 状态定义
  const [coachDetail, setCoachDetail] = useState<CoachDetailItem | null>(null);
  const [coachPrices, setCoachPrices] = useState<CoachPriceItem[]>([]);
  const [honorWall, setHonorWall] = useState<any[]>([]);
  const [coachComments, setCoachComments] = useState<CoachCommentItem[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>('');
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [commentsTotal, setCommentsTotal] = useState<number>(0);
  const [loadingMore, setLoadingMore] = useState<boolean>(false);
  const [commentsLoading, setCommentsLoading] = useState<boolean>(false);
  const [showCertificate, setShowCertificate] = useState<boolean>(false);
  // 回复相关状态
  const [replyEditing, setReplyEditing] = useState<{[key: number]: boolean}>({});
  const [replyContent, setReplyContent] = useState<{[key: number]: string}>({});

  // 加载教练详情数据
  const loadCoachDetail = async () => {
    setIsLoading(true);
    setError('');
    await getCoachDetailApi(coachId).then(async(res) => {
      if (res.code === 200) {
        if (res.data.video) {
          res.data.video = await assetsFileUrl(res.data.video);
        }
        setCoachDetail(res.data);
      } else {
        setCoachDetail(null);
        setError('获取教练详情失败');
      }
    }).catch(err => {
      console.log("获取教练详情错误:", err)
      setCoachDetail(null);
      setError('获取教练详情错误');
    }).finally(() => {
      setIsLoading(false);
    });
  };

  // 加载价格套餐数据
  const loadCoachPrices = async () => {
    try {
      setCoachPrices([]);
      await getCoachPricesApi(coachId).then(res => {
        if (res.code === 200) {
          setCoachPrices(res.data);
        }
      });
    } catch (err) {
      console.error('加载价格套餐数据错误:', err);
    }
  };

  // 加载荣誉墙数据
  const loadHonorWall = async () => {
    try {
      await getCoachHonorWallApi(coachId).then(res => {
        if (res.code === 200) {
          const honorWall = res.data.map(item => item);
          setHonorWall(honorWall);
        }
      });
    } catch (err) {
      console.error('加载荣誉墙数据错误:', err);
    }
  };

  // 获取教练的评论区内容
  const loadCoachComments = async (page: number = 1) => {
    if (!coachId) return;
    if (isRequesting.current || commentsLoading || !hasMore) {
      return;
    }
    isRequesting.current = true;
    if (page > 1) setLoadingMore(true);
    else setCommentsLoading(true);

    await getCoachCommentsApi(coachId, page || 1, pageSize).then(response => {
      if(response.code === 200) {
        // 修正总评论数访问路径
        setCommentsTotal(response.total as number);
        const newComments = Array.isArray(response.data) ? response.data : [];
        if (page === 1) {
          setCoachComments(newComments);
        } else {
          setCoachComments(prev => prev ? [...prev, ...newComments] : newComments);
        }
        // 根据总评论数和当前页码计算是否有更多数据
        setHasMore(response.has_more || false);
      }else {
        Taro.showToast({
          title: '加载评论失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      Taro.showToast({
        title: '加载评论失败',
        icon: 'none'
      });
    }).finally(() => {
      isRequesting.current = false;
      if (page > 1) setLoadingMore(false);
      else setCommentsLoading(false);
    });
  };

  // 实现无限滚动加载更多数据的函数
  const fetchMoreData = async () => {
    if (hasMore && !isRequesting.current) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      await loadCoachComments(nextPage);
    }
  };

  const onAttachmentsUpdate = (commentId: number, attachments: CommentAttachmentItem[]) => {
    if (coachComments && coachComments.length > 0) {
      setCoachComments(pre => pre?.map(comment => {
        if (comment.id === commentId) {
          return {
            ...comment,
            attachments,
          }
        }
        return comment;
      }) || []
      );
    }
  };

  // 删除回复（支持嵌套回复的删除）
  const deleteReply = async(replyId: number, isComment: boolean) => {
    try {
      const response = await deleteCommentOrReplyApi(replyId, coachId, isComment);
      if (response.code === 200) {
        // 递归过滤所有层级的回复
        const filterReplies = (replies: CoachCommentItem[]): CoachCommentItem[] => {
          return replies.reduce((acc, reply) => {
            // 如果当前回复是要删除的，不添加到结果中
            if (reply.id === replyId) {
              return acc;
            }

            // 如果有嵌套回复，递归处理并更新计数
            if (reply.reply && reply.reply.length > 0) {
              const originalLength = reply.reply.length;
              reply.reply = filterReplies(reply.reply);
              const newLength = reply.reply.length;
              
              // 如果嵌套回复数量减少，更新reply_count
              if (originalLength > newLength) {
                reply.answer = Math.max(0, (reply.reply_count || 0) - (originalLength - newLength));
                reply.reply_count = reply.answer;
              }
            }

            acc.push(reply);
            return acc;
          }, [] as CoachCommentItem[]);
        };
        
        setCoachComments(prev => prev ? filterReplies(prev) : []);
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('Failed to delete reply:', err);
      Taro.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  };

  // 处理点赞评论
  const handleLikeComment = async (commentId: number) => {
    try {
      // 首先查找当前评论的点赞状态
      let currentComment: CoachCommentItem | undefined;
      const findComment = (comments: CoachCommentItem[]): void => {
        for (const comment of comments) {
          if (comment.id === commentId) {
            currentComment = comment;
            return;
          }
          if (comment.reply && comment.reply.length > 0) {
            findComment(comment.reply);
            if (currentComment) return;
          }
        }
      };
      findComment(coachComments);
      
      if (!currentComment) {
        Taro.showToast({ title: '评论不存在', icon: 'none' });
        return;
      }
      
      const response = await setCoachCommentFavoriteApi({
        comment_id: commentId,
        coach_id: coachId,
        is_favorite: !currentComment.has_favorite
      });
      
      if (response.code === 200) {
        // 更新本地状态
        setCoachComments(prev => prev?.map(comment => {
          if (comment.id === commentId) {
            return {
              ...comment,
              is_favorite: !comment.has_favorite,
              favorites_count: comment.has_favorite 
                ? (comment.favorite || 0) - 1 
                : (comment.favorite || 0) + 1
            };
          }
          // 递归处理嵌套回复
          if (comment.reply && comment.reply.length > 0) {
            const updateNestedLikes = (replies: CoachCommentItem[]): CoachCommentItem[] => {
              return replies.map(reply => {
                if (reply.id === commentId) {
                  return {
                    ...reply,
                    is_favorite: !reply.has_favorite,
                    favorites_count: reply.has_favorite 
                      ? (reply.favorite || 0) - 1 
                      : (reply.favorite || 0) + 1
                  };
                }
                if (reply.reply && reply.reply.length > 0) {
                  reply.reply = updateNestedLikes(reply.reply);
                }
                return reply;
              });
            };
            comment.reply = updateNestedLikes(comment.reply);
          }
          return comment;
        }) || []);
      } else {
        Taro.showToast({
          title: response.message || '点赞失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('点赞失败:', error);
      Taro.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  };

  // 加载所有数据
  const loadAllData = async () => {
    setIsLoading(true);
    setError('');
    try {
      await loadCoachDetail();
      await loadCoachPrices();
      await loadHonorWall();
      await loadCoachComments(1);
    } catch (err) {
      setError('网络异常，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    if (!isInitialized.current && baseId && coachId) {
      loadAllData();
      isInitialized.current = true;
    }
  }, [baseId, coachId]);

  // 重试加载数据
  const handleRetry = () => {
    loadAllData();
  };

  // 联系教练
  const handleContactCoach = (phoneNumber: string) => {
    if (!phoneNumber) {
      Taro.showToast({
        title: '该教练尚未开放手机号码！',
        icon: 'none'
      });
      return;
    }
    Taro.makePhoneCall({
      phoneNumber: phoneNumber,
      success: () => {
        console.log('拨打电话成功');
      },
      fail: (err) => {
        console.error('拨打电话失败:', err);
        Taro.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  };

  // 咨询教练
  const handleConsultCoach = () => {
    getCoachSessionIdApi(coachId, coachDetail?.username || '').then(response => {
      if(response.code === 200) {
        Taro.navigateTo({
          url: `/pages/chat/index?sessionId=${response.data}&coachId=${coachId}&coachName=${encodeURIComponent(coachDetail?.username || '')}&coachAvatar=${encodeURIComponent(coachDetail?.avatar || '')}&source=1`
        });
      }else {
        Taro.showToast({
          title: '获取会话id失败',
          icon: 'none'
        });
      }
    }).catch(() => {
      Taro.showToast({
        title: '获取会话id失败',
        icon: 'none'
      });
    })
  };

  // 查看教练执照信息
  const handleViewCertificate = () => {
    setShowCertificate(true);
  };

  // 关闭执照信息模态框
  const handleCloseCertificate = () => {
    setShowCertificate(false);
  };

  // 渲染价格卡片
  const renderPriceCard = (priceItem: CoachPriceItem) => {
    return (
      <View className="coach-price-card" key={priceItem.id}>
        <View className="coach-price-card-header">
          <Text className="coach-price-card-title">{priceItem.name}</Text>
          <Text className="coach-price-value">¥{priceItem.price}</Text>
        </View>
        <View className="coach-price-card-details">
          <Text className="coach-price-detail-item">
            <Text className="coach-price-detail-label">适用驾照类型：</Text>
            <Text className="coach-price-detail-value">{priceItem.license}</Text>
          </Text>
          <Text className="coach-price-detail-item">
            <Text className="coach-price-detail-label">每次练车时长：</Text>
            <Text className="coach-price-detail-value">{priceItem.runtime}小时</Text>
          </Text>
          <Text className="coach-price-detail-item">
            <Text className="coach-price-detail-label">其他信息：</Text>
            <Text className="coach-price-detail-value">{priceItem.description}</Text>
          </Text>
        </View>
      </View>
    );
  };

  // 渲染荣誉墙统计数据
  const renderHonorStats = () => {
    return (
      <View className="coach-honor-stats-grid">
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">月度报名：</Text>
          <Text className="purple-tag">{coachDetail?.mouth_student || 0}人</Text>
        </View>
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">月度毕业：</Text>
          <Text className="cyan-tag">{coachDetail?.mouth_graduate || 0}人</Text>
        </View>
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">学生总数：</Text>
          <Text className="lime-tag">{coachDetail?.student_total || 0}人</Text>
        </View>
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">年度报名：</Text>
          <Text className="purple-tag">{coachDetail?.year_student || 0}人</Text>
        </View>
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">年度毕业：</Text>
          <Text className="lime-tag">{coachDetail?.year_graduate || 0}人</Text>
        </View>
        <View className="coach-honor-stat-item">
          <Text className="coach-honor-stat-label">毕业总数：</Text>
          <Text className="cyan-tag">{coachDetail?.graduate_total || 0}人</Text>
        </View>
      </View>
    );
  };

  // 渲染荣誉墙图片
  const renderHonorImages = () => {
    return honorWall.map((honor, index) => (
      <View className="coach-honor-image-item" key={index}>
        <ImageLoader 
            className="coach-honor-image" 
            src={honor.image || honor.imageUrl} 
            mode="aspectFill"
        />
      </View>
    ));
  };

  // 渲染评论项（支持嵌套回复）
  const renderCommentItem = (comment: CoachCommentItem) => {
    return (
      <View className="coach-comment-item" key={comment.id}>
        <View className="coach-comment-header">
          <ImageLoader 
            className="coach-commenter-avatar" 
            src={comment.user.avatar || ''} 
            mode="aspectFill"
          />
          <View className="coach-commenter-info">
            <Text className="coach-commenter-name">{comment.user.username}</Text>
            <Text className="coach-comment-time">{comment.created_at}</Text>
          </View>
          <View className="coach-comment-score">
            <ScoreStar score={comment.score || 5} size={10}/>
          </View>
        </View>
        <Text className="coach-comment-content">{comment.content}</Text>
        {comment.attachments && comment.attachments.length > 0 && (
          <View className="coach-comment-attachments">
            {comment.attachments.map((attachment, index) => (
              <ImageLoader 
                key={index} 
                className="coach-attachment-image" 
                src={attachment.image || ''} 
                mode="aspectFill"
              />
            ))}
          </View>
        )}
        <View className="coach-comment-actions">
            <View className="coach-like-button" onClick={() => handleLikeComment(comment.id)}>
                <MaterialIcons name="heart" className={`coach-like-icon ${comment.has_favorite ? 'liked' : ''}`} size={16} />
                <Text className="coach-like-count">{comment.favorite || 0}</Text>
            </View>
            <View className="coach-like-button" onClick={() => handleLikeComment(comment.id)}>
                <MaterialIcons name="thumb_down" className={`coach-like-icon ${comment.has_dislike ? 'liked' : ''}`} size={16} />
                <Text className="coach-like-count">{comment.has_dislike || 0}</Text>
            </View>
            {comment.is_edit && (
              <>
                <View className="coach-delete-button" onClick={() => deleteReply(comment.id, true)}>
                    <MaterialIcons name="delete" color="#ff4d4f" size={16} />
                </View>
                {/* 编辑按钮 - 仅发帖人可见 */}
                <View className="coach-edit-button" onClick={() => {
                  setReplyEditing(prev => ({ ...prev, [comment.id]: true }));
                  setReplyContent(prev => ({ ...prev, [comment.id]: comment.content }));
                }}>
                    <MaterialIcons name="edit" color="#1890ff" size={16} />
                </View>
              </>
            )}
          </View>
      </View>
    );
  };

  // 渲染加载状态
  if (isLoading) {
    return (
      <DataLoadingView />
    );
  }

  // 渲染错误状态
  if (error) {
    return (
      <DataErrorView content={error} onClickFunc={handleRetry}/>
    );
  }

  if (!coachDetail) {
    
    return (
      <EmptyContent title='未找到教练信息'/>
    );
  }

  return (
    <View className="page-container">
      {/* 顶部导航栏 */}
      <PageHeader title="教练详情" />

      {/* 教练头部信息 */}
      <View className="coach-header-section">
        <View className="coach-header-image">
          {coachDetail.video ? (
            <Video
              src={coachDetail.video}
              className="coach-header-video"
              controls
            />
          ) : (
            <UserAvatarImage 
              class_name="coach-header-avatar"
              avatar={coachDetail.avatar}
              user_id={coachDetail.id}
              user_name={coachDetail.username}
            />
          )}
          <View className="coach-header-overlay">
            <View className="coach-header-score">
              <ScoreStar score={coachDetail.rating || 5} inactiveColor="#f0f0f0" />
            </View>
            <View className={`coach-header-status ${coachDetail.is_full ? 'coach-status-full' : 'coach-status-available'}`}>
              {coachDetail.is_full ? '已满员' : '可报名'}
            </View>
          </View>
        </View>
      </View>

      <View className="coach-content-scroll-view">
          {/* 教练信息 */}
        <View className="coach-info-section">
            <View className="coach-info-card">
              <View className="coach-info-center">
                <View className="coach-profile-avatar">
                  <UserAvatarImage 
                    class_name="coach-avatar-image"
                    avatar={coachDetail.avatar}
                    user_id={coachDetail.id}
                    user_name={coachDetail.username}
                  />
                </View>
                <View className="coach-basic-info">
                  <View className="coach-name-row">
                    <Text className="coach-name text-lg">{coachDetail.username}</Text>
                    <UserGenderImage gender={coachDetail.gender || ''} />
                  </View>
                  
                  <View className="coach-details-tags">
                    <View className="purple-tag text-md">{coachDetail.age}岁</View>
                    <View className="magenta-tag text-md">教龄{coachDetail.experience_years}年</View>
                    <View className="lime-tag text-md">籍贯:{coachDetail.native}</View>
                    {coachDetail.school && <Text className="cyan-tag text-md">{coachDetail.school}</Text>}
                  </View>
                  <View className="coach-licenses">
                    {coachDetail.licenses && (
                      <LicenseTags licenseItems={coachDetail.licenses || []} />
                    )}
                    {coachDetail.certificate && (
                    <View 
                      className="coach-certificate-button"
                      onClick={handleViewCertificate}
                    >
                      查看教练执照信息
                    </View>
                    )}
                  </View>
                </View>
              </View>
            </View>

            {/* 接送信息 */}
            <View className="coach-pickup-info-card">
              <Text className="coach-card-title">
                <MaterialIcons name="place" className="coach-card-icon" color="#1890ff" size={16} />
                接送服务
              </Text>
              <View className="coach-pickup-tags">
                <Text className="lime-tag text-md">教练地铁站3公里接送</Text>
                <Text className="ml-5 orange-tag text-md">平台赠送百公里上门接送服务</Text>
              </View>
            </View>

            {/* 联系方式 */}
            <View className="coach-contact-card">
              <Text className="coach-card-title">
                <MaterialIcons name="phone" className="coach-card-icon" color="#52c41a" size={24} />
                联系方式
              </Text>
              <View className="coach-contact-buttons">
                <View className="coach-consult-button" onClick={handleConsultCoach}>
                  <MaterialIcons name="comment" className="coach-button-icon" size={20} color='#ffffff'/>
                  立即咨询
                </View>
                <View className="coach-call-button" onClick={() => handleContactCoach(coachDetail.phone || '')}>
                  <MaterialIcons name="phone" className="coach-button-icon" size={20} color='#ffffff'/>
                  电话了解
                </View>
              </View>
            </View>

            {/* 荣誉墙 */}
            <View className="coach-honor-wall-card">
              <Text className="coach-card-title">
                <MaterialIcons name="trophy" className="coach-card-icon" color="#531dab" size={16} />
                荣誉墙
              </Text>
              {renderHonorStats()}
              {honorWall.length > 0 && (
                <View className="coach-honor-images-grid">
                  {renderHonorImages()}
                </View>
              )}
            </View>

            {/* 价格套餐 */}
            <View className="coach-prices-card">
              <Text className="coach-card-title">
                <MaterialIcons name="directions_car" className="coach-card-icon" color="#08979c" size={16} />
                价目表
              </Text>
              <View className="coach-prices-list">
                {coachPrices.map(priceItem => renderPriceCard(priceItem))}
              </View>
            </View>

            {/* 评论区 */}
            <ScrollView className="coach-comments-card">
              <Text className="coach-card-title">
                <MaterialIcons name="comment" className="coach-card-icon" color="#c41d7f" size={16} />
                学员评价 ({commentsTotal})
              </Text>
              {commentsLoading ? (
                <View className="coach-comments-loading">
                  <View className="coach-loading-spinner"></View>
                </View>
              ) : coachComments.length > 0 ? (
                <View className="coach-comments-list">
                  {coachComments.map(comment => (
                    <View key={comment.id} className="coach-comment-wrapper">
                      {renderCommentItem(comment)}
                    </View>
                  ))}
                  {loadingMore && (
                    <View className="coach-loading-more">
                      <View className="coach-loading-spinner small"></View>
                    </View>
                  )}
                  {!hasMore && !loadingMore && coachComments.length > 0 && (
                    <View className="coach-no-more-comments">
                      <Text className="coach-no-more-text">我也是有底线的哦~</Text>
                    </View>
                  )}
                </View>
              ) : (
                <View className="coach-no-comments">
                  <Text className="coach-no-comments-text">暂无评论</Text>
                </View>
              )}
            </ScrollView>
        </View>

        {/* 底部空间，确保内容不被底部按钮遮挡 */}
        <View style={{ height: 100 }}></View>
      </View>

      {/* 执照图片模态框 */}
      {showCertificate && (
          <View className="coach-certificate-modal">
          <View className="coach-modal-overlay" onClick={handleCloseCertificate}></View>
          <View className="coach-modal-content">
            <View className="coach-modal-header">
              <Text className="coach-modal-title">教练执照信息</Text>
              <View className="coach-modal-close" onClick={handleCloseCertificate}>
                <Text className="coach-close-icon">
                  <MaterialIcons name="close" size={20} />
                </Text>
              </View>
            </View>
            <View className="coach-modal-body">
              {coachDetail?.certificate ? (
                <ImageLoader 
                  src={coachDetail.certificate} 
                  className="coach-certificate-image"
                  mode="aspectFit"
                />
              ) : (
                <View className="coach-no-certificate">
                  <Text className="coach-no-certificate-text">暂无执照信息</Text>
                </View>
              )}
            </View>
          </View>
        </View>
      )}
    </View>
  );
};

export default CoachDetailPage;